package com.springboot.helloworld.handle;

import com.springboot.helloworld.bean.Result;
import com.springboot.helloworld.controller.BaseController;
import com.springboot.helloworld.enums.ResultEnum;
import com.springboot.helloworld.exception.GirlException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @version v1.0
 * @description: 全局异常捕获
 * @author: xiaoliang.liu
 * @date: 2018/7/2 0:20
 */
@Slf4j
@ControllerAdvice
public class ExceptionHandle extends BaseController {

    /**
     * 处理异常，返回统一格式的异常
     *
     * @param e 捕获到的异常
     * @return Result
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handle(Exception e) {
        if (e instanceof GirlException) {
            log.error("异常", e);
            return fail(((GirlException) e).getCode(), e.getMessage());
        }
        log.error("【系统异常】", e);
        return fail(ResultEnum.UNKNOWN_ERROR.getCode(), ResultEnum.UNKNOWN_ERROR.getMsg());
    }
}
